#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::cerr;
using std::string;


#include <unistd.h>
#include <pthread.h> // 线程库
#include <sys/types.h>

string buf[5] = {string()}; //五个字符串保存商品
int arr[5] = {0}; //记录是否有商品在buf中
int oper[5] = {0}; //记录是否有线程在操作此buf

string get(int bufid) //获取商品
{
    return buf[bufid];
}

void put(int bufid) //存放商品
{
    char s[64] = {0};
    sprintf(s,"%d",bufid);
    buf[bufid] = string(s);
}

void *threadp(void* args) //生产者
{
    int i = 0;
    while(true) //查找没用被线程操作且buf资源为空的位置
    {
        if(oper[i] == 0 && arr[i] == 0) //没有线程操作且没有商品中其中
        {
            oper[i] = 1;
            put(i); //向i位置buf中写入数据
            arr[i] = 1;
            oper[i] = 0;
        }
        cout<<((char*)args)<<"生产中..."<<endl;
        ++i;
        if(i == 5) i = 0;
        sleep(1);
    }
}

void *threadc(void* args) //消费者
{
    int i = 0;
    while(true) //查找没用被线程操作且buf资源存在
    {
        if(oper[i] == 0 && arr[i] == 1) //没有线程操作且有商品中其中
        {
            oper[i] = 1;
            cout << ((char*)args) << "消费:" <<  get(i) << endl; //向i位置buf中写入数据
            arr[i] = 0;
            oper[i] = 0;
        }
        ++i;
        if(i == 5) i = 0;
        sleep(1);
    }
}

int main()
{
    pthread_t tp1,tp2,tc1,tc2; //四个线程
    char s1[64] = "生产者1";
    char s2[64] = "生产者2";
    char s3[64] = "消费者1";
    char s4[64] = "消费者2";
    pthread_create(&tp1,nullptr,threadp,(void*)s1);
    pthread_create(&tp2,nullptr,threadp,(void*)s2);
    pthread_create(&tc1,nullptr,threadc,(void*)s3);
    pthread_create(&tc2,nullptr,threadc,(void*)s4);
    while(true);

    cout<<"线程退出!信号量共享资源销毁!"<<endl;
}